package com.chuangfeng.framework.core.common.page;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 防止SQL注入攻击的过滤器
 * @author 佛笑 xiedayun2008@163.com
 *
 */
public class SqlFilter implements Filter{

	/**
	 * 过滤器上下文配置
	 */
	private FilterConfig filterConfig;
	
	/**
	 * 过滤字符串
	 */
	private String filterStr;
	
	
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		
		//获取请求的参数名
		Enumeration keys = req.getParameterNames();
		StringBuffer valueStr = new StringBuffer();
		while(keys.hasMoreElements()){
			String name = keys.nextElement().toString();
			String value[] = req.getParameterValues(name);
			for(String one : value){
				valueStr.append(one);
			}
		}
		if(valueStr.length()<=0){
			chain.doFilter(request, response);
		}else if(this.sqlValidate(valueStr.toString())){
			req.setAttribute("error", "您提交的请求参数中含有不安全的字符！请勿如此操作！");
			res.sendRedirect(req.getContextPath()+"/common/pages/messages.jsp");
		}else{
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		this.filterConfig = arg0;
		this.filterStr = arg0.getInitParameter("filterStr");
	}
	
	/**
	 * 校验SQL值范围
	 * @param value
	 * @return
	 */
	public boolean sqlValidate(String value){
		value = value.toLowerCase();         //统一转换小写
		String filterStrs[] = this.filterStr.split("|");
		for(String filter : filterStrs){
			if(filter.indexOf(value)!=-1){
				return true;
			}
		}
		return false;
	}

}
